package com.atguigu.springboot.controller;

import com.atguigu.springboot.exception.UserNotExistException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author admin
 * @create 2019-04-07 18:45
 */
@ControllerAdvice
public class MyExceptionHandler {

    //1、浏览器和客户端返回的都是json
    /*@ResponseBody
    @ExceptionHandler(UserNotExistException.class)
    public Map exceptionHandler(Exception e){
        Map<String,Object> map = new HashMap <String,Object>();
        map.put("code","user.notexist");
        map.put("message",e.getMessage());
        return map;
    }*/


    @ExceptionHandler(UserNotExistException.class)
    public String exceptionHandler(Exception e, HttpServletRequest request){
        Map<String,Object> map = new HashMap <String,Object>();
        request.setAttribute("javax.servlet.error.status_code",500);
        map.put("code","user.notexist");
        map.put("message","用户出错了");
        request.setAttribute("ext",map);
        return "forward:/error";
    }
}
